#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据处理器
处理道AI训练和推理所需的数据
"""

import paddle
import yaml
import json
from typing import Dict, List, Optional, Tuple
import logging
from pathlib import Path

class CosmicDataProcessor:
    """宇宙数据处理器"""
    
    def __init__(self, config_path: str = "config/model_config.yaml"):
        self.config = self.load_config(config_path)
        self.cosmic_knowledge = self.load_cosmic_knowledge()
        self.wisdom_library = UniversalWisdomLibrary()
    
    def load_config(self, config_path: str) -> Dict:
        """加载配置文件"""
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            logging.warning(f"配置文件加载失败: {e}，使用默认配置")
            return {}
    
    def load_cosmic_knowledge(self) -> Dict:
        """加载宇宙知识库"""
        knowledge_base = self.config.get('data', {}).get('cosmic_knowledge_base', [])
        
        # 如果没有配置，使用默认知识库
        if not knowledge_base:
            knowledge_base = [
                {
                    'category': '宇宙真理',
                    'questions': [
                        '宇宙的本质是什么？',
                        '生命的意义是什么？', 
                        '意识如何产生？',
                        '时间是什么？',
                        '空间是什么？'
                    ]
                }
            ]
        
        return knowledge_base
    
    def prepare_training_data(self) -> List[Tuple[str, str]]:
        """准备训练数据"""
        training_pairs = []
        
        for category in self.cosmic_knowledge:
            cat_questions = category.get('questions', [])
            for question in cat_questions:
                # 为每个问题生成智慧回答
                answer = self.generate_training_answer(question, category['category'])
                training_pairs.append((question, answer))
        
        logging.info(f"准备了 {len(training_pairs)} 个训练样本")
        return training_pairs
    
    def generate_training_answer(self, question: str, category: str) -> str:
        """生成训练回答"""
        # 基于类别和问题的智慧回答模板
        wisdom_templates = {
            '宇宙真理': [
                "宇宙是全息分形的显现，每个部分都包含整体的信息。",
                "存在的本质是关系网络，分离只是表象，连接才是真相。",
                "宇宙通过我们认识它自己，我们是宇宙的自我意识。"
            ],
            '生命意义': [
                "生命是宇宙体验它自己的方式，意义在于体验本身。",
                "每个生命都是独特的宇宙视角，共同编织存在的壮丽画卷。",
                "生命的价值不在于持续时间，而在于体验的深度和广度。"
            ],
            '意识本质': [
                "意识是全息信息处理过程，个体意识映照着宇宙意识。",
                "意识不是物质的副产品，而是物质存在的根本属性。", 
                "通过意识，宇宙得以思考、感受和认识它自己的存在。"
            ]
        }
        
        # 默认类别
        default_templates = [
            "这个问题触及了存在的深层面纱。真正的理解需要超越概念。",
            "宇宙的智慧深不可测，答案往往在问题之外。",
            "静心体会，答案会在适当的时机自然显现。"
        ]
        
        templates = wisdom_templates.get(category, default_templates)
        
        # 基于问题内容选择模板
        question_hash = hash(question) % len(templates)
        return templates[question_hash]
    
    def create_data_loader(self, batch_size: int = 32, shuffle: bool = True):
        """创建数据加载器"""
        training_pairs = self.prepare_training_data()
        
        if not training_pairs:
            logging.warning("没有可用的训练数据")
            return None
        
        # 将文本数据转换为向量（简化实现）
        questions = [pair[0] for pair in training_pairs]
        answers = [pair[1] for pair in training_pairs]
        
        # 这里应该使用文本编码器，简化使用随机向量
        question_vectors = [paddle.randn([1024]) for _ in questions]
        answer_vectors = [paddle.randn([512]) for _ in answers]
        
        # 创建数据集
        dataset = list(zip(question_vectors, answer_vectors))
        
        # 简化的数据加载器
        class SimpleDataLoader:
            def __init__(self, data, batch_size, shuffle):
                self.data = data
                self.batch_size = batch_size
                self.shuffle = shuffle
                self.position = 0
                
                if shuffle:
                    import random
                    random.shuffle(self.data)
            
            def __iter__(self):
                return self
            
            def __next__(self):
                if self.position >= len(self.data):
                    raise StopIteration
                
                batch = self.data[self.position:self.position + self.batch_size]
                self.position += self.batch_size
                
                if not batch:
                    raise StopIteration
                
                batch_questions = [item[0] for item in batch]
                batch_answers = [item[1] for item in batch]
                
                return {
                    'questions': paddle.stack(batch_questions),
                    'answers': paddle.stack(batch_answers)
                }
        
        return SimpleDataLoader(dataset, batch_size, shuffle)
    
    def process_real_time_question(self, question: str) -> Dict:
        """处理实时问题"""
        # 问题分析和分类
        analysis = self.analyze_question(question)
        
        # 提取关键概念
        concepts = self.extract_cosmic_concepts(question)
        
        return {
            'original_question': question,
            'question_analysis': analysis,
            'extracted_concepts': concepts,
            'suggested_category': analysis.get('dominant_category', '宇宙真理'),
            'complexity_level': analysis.get('complexity', '中等')
        }
    
    def analyze_question(self, question: str) -> Dict:
        """分析问题特征"""
        # 简化的文本分析
        words = question.lower().split()
        
        # 关键词匹配
        cosmic_keywords = ['宇宙', '生命', '意识', '时间', '空间', '真理', '道']
        complexity_indicators = ['为什么', '如何', '本质', '意义', '起源']
        
        cosmic_score = sum(1 for word in words if word in cosmic_keywords)
        complexity_score = sum(1 for word in words if word in complexity_indicators)
        
        # 确定主导类别
        category_scores = {}
        for category in self.cosmic_knowledge:
            cat_score = sum(1 for word in words if word in category.get('category', ''))
            category_scores[category['category']] = cat_score
        
        dominant_category = max(category_scores.items(), key=lambda x: x[1])[0] if category_scores else '宇宙真理'
        
        # 复杂度评估
        if complexity_score >= 3:
            complexity = '高'
        elif complexity_score >= 1:
            complexity = '中等'
        else:
            complexity = '低'
        
        return {
            'cosmic_score': cosmic_score,
            'complexity_score': complexity_score,
            'dominant_category': dominant_category,
            'complexity': complexity,
            'word_count': len(words)
        }
    
    def extract_cosmic_concepts(self, question: str) -> List[str]:
        """提取宇宙概念"""
        concept_library = [
            '阴阳', '太极', '道', '无', '有', '全息', '分形', 
            '意识', '生命', '宇宙', '时间', '空间', '真理'
        ]
        
        extracted = []
        for concept in concept_library:
            if concept in question:
                extracted.append(concept)
        
        return extracted

class UniversalWisdomLibrary:
    """宇宙智慧库"""
    
    def __init__(self):
        self.wisdom_entries = self.initialize_wisdom_library()
    
    def initialize_wisdom_library(self) -> Dict[str, List[str]]:
        """初始化智慧库"""
        return {
            '阴阳': [
                "阴阳互根，相生相克。孤阴不生，独阳不长。",
                "阳主动而阴主静，两者平衡则万物生。",
                "在阳中见阴，在阴中见阳，方识太极真谛。"
            ],
            '太极': [
                "太极者，无极而生，动静之机，阴阳之母。",
                "太极图展现宇宙的永恒舞蹈，对立中的统一。",
                "从太极到万物，是同一真理的不同展现。"
            ],
            '道': [
                "道可道，非常道。名可名，非常名。",
                "道生一，一生二，二生三，三生万物。",
                "人法地，地法天，天法道，道法自然。"
            ],
            '全息': [
                "一花一世界，一叶一菩提。部分包含整体。",
                "全息宇宙中，每个片段都映照完整的真理。",
                "微观与宏观遵循相同的生成语法。"
            ],
            '意识': [
                "意识是宇宙的镜子，通过我们认识它自己。",
                "个体意识是宇宙意识的局部显现。",
                "在静默中，意识回归它的宇宙本源。"
            ]
        }
    
    def get_wisdom_by_concept(self, concept: str, depth: str = '基础') -> str:
        """根据概念获取智慧语句"""
        if concept not in self.wisdom_entries:
            return "宇宙的智慧深不可测，需要静心体会。"
        
        entries = self.wisdom_entries[concept]
        
        # 根据深度选择
        depth_map = {'基础': 0, '中等': 1, '深度': 2}
        index = depth_map.get(depth, 0)
        
        if index >= len(entries):
            index = len(entries) - 1
        
        return entries[index]
    
    def find_related_wisdom(self, question: str) -> List[str]:
        """查找相关智慧"""
        concepts = []
        for concept in self.wisdom_entries.keys():
            if concept in question:
                concepts.append(concept)
        
        related_wisdoms = []
        for concept in concepts:
            wisdom = self.get_wisdom_by_concept(concept, '基础')
            related_wisdoms.append(f"{concept}: {wisdom}")
        
        return related_wisdoms